//
//  Transition.m
//  ImGuider
//
//  Created by 王鹏宇 on 2017/4/13.
//  Copyright © 2017年 imguider. All rights reserved.
//

#import "Transition.h"
#import "MainViewController.h"

@interface Transition()

@end
@implementation Transition


/**
 
 *   设定转场类型
 
 */
+ (instancetype)transitionWithTransitionType:(TransitionType)type {
    return [[self alloc] initWithTransitionType:type];
}

- (instancetype)initWithTransitionType:(TransitionType)type {
    self = [super init];
    if (self) {
        self.type = type;
    }
    return self;
}


// 取快照

- (UIImage *)imageFromView:(UIView *)snapView {
    UIGraphicsBeginImageContext(snapView.frame.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [snapView.layer renderInContext:context];
    UIImage *targetImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return targetImage;
}

/**
 *  设定某个view的相对固定点
 *
 *  @param point 固定点位置
 *  @param View  指定View
 */
- (void)setAnchorPointTo:(CGPoint)point withView:(UIView *)View{
    View.frame = CGRectOffset(View.frame, (point.x - View.layer.anchorPoint.x) * View.frame.size.width, (point.y - View.layer.anchorPoint.y) * View.frame.size.height);
    View.layer.anchorPoint = point;
}


/**
 *  设定转场时间
 *
 *  @param transitionContext 转场的上下文
 *
 *  @return 时间
 */
- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext {
    switch (_type) {
        
        case PageCoverTransitionPush:
            
        case PageCoverTransitionPop:
        {
            return 0.5;
        }
            break;
       
        default:
            return 0.5;
            break;
    }
}

- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext {
    switch (_type) {
        
        case PageCoverTransitionPush:
        {
            [self PageCoverPushAnimation:transitionContext];
        }
            break;
        case PageCoverTransitionPop:
        {
            [self PageCoverPopAnimation:transitionContext];
        }
            break;
        
        default:
            break;
    }
}

#pragma  mark - 翻页转场 push 动画

- (void)PageCoverPushAnimation:(id<UIViewControllerContextTransitioning>)transitionContext {
    MainViewController *fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    BaseViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];

    UITableViewCell * cell = [fromVC.tableView cellForRowAtIndexPath:fromVC.currentIndexPath];
    UIImageView *MoveView = [[UIImageView alloc] initWithImage:[self imageFromView:cell]];
    MoveView.tag = 1024;
    cell.hidden = YES;
    UIView *containerView = [transitionContext containerView];
    MoveView.frame = [cell convertRect:cell.bounds toView:containerView];
    toVC.animationView = MoveView;
    //获取做动画的页面 一般动画都放在 containerView 中
    //[containerView addSubview:toVC.view];
    [containerView addSubview:MoveView];
    [containerView insertSubview:toVC.view atIndex:0];
    //设置相对固定点
    [self setAnchorPointTo:CGPointMake(0, 0.5) withView:MoveView];
    //设置三维旋转
    CATransform3D transform3D = CATransform3DIdentity;//单位矩阵
    transform3D.m34 = - 0.002;//m34（透视效果，要操作的这个对象要有旋转的角度，否则没有效果。正直/负值都有意义）
    containerView.layer.sublayerTransform = transform3D;
    
    
    
    //增加阴影效果
//    CAGradientLayer *fromGradient = [CAGradientLayer layer];//可以方便的处理颜色渐变
//    fromGradient.frame = fromVC.view.bounds;
//    fromGradient.colors = @[(id)[UIColor whiteColor].CGColor, (id)[UIColor whiteColor].CGColor];
//    fromGradient.startPoint = CGPointMake(0.0, 0.5);
//    fromGradient.endPoint = CGPointMake(0.8, 0.5);
//    
//    UIView *fromShadow = [[UIView alloc] initWithFrame:fromVC.view.bounds];
//    fromShadow.backgroundColor = [UIColor clearColor];
//    [fromShadow.layer insertSublayer:fromGradient atIndex:1];
//    fromShadow.alpha = 0.0;
//    [MoveView addSubview:fromShadow];
//    CAGradientLayer *toGradient = [CAGradientLayer layer];
//    toGradient.frame = toVC.view.bounds;
//    toGradient.colors = @[(id)[UIColor whiteColor].CGColor,
//                          (id)[UIColor whiteColor].CGColor];
//    toGradient.startPoint = CGPointMake(0.0, 0.5);
//    toGradient.endPoint = CGPointMake(0.8, 0.5);
//    UIView *toShadow = [[UIView alloc]initWithFrame:MoveView.frame];
//    toShadow.backgroundColor = [UIColor whiteColor];
//    //[toShadow.layer insertSublayer:toGradient atIndex:1];
//    toShadow.alpha = 1.0;
//    [containerView addSubview:toShadow];
    
    
   // fromVC.view.hidden = YES;
    [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
        
        MoveView.layer.transform = CATransform3DMakeRotation(- M_PI_2, 0, 1, 0);
        MoveView.frame = fromVC.view.bounds;
        
        fromVC.view.alpha = 0;
    } completion:^(BOOL finished) {
        fromVC.view.alpha = 1;
        cell.hidden = NO;
        containerView.layer.sublayerTransform = CATransform3DIdentity;
        [MoveView removeFromSuperview];
        [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
        
       // containerView.layer.sublayerTransform = CATransform3DIdentity;
        if ([transitionContext transitionWasCancelled])
        {
            [MoveView removeFromSuperview];
        }
    }];
}

#pragma  mark - 翻页转场 pop 动画

- (void)PageCoverPopAnimation:(id<UIViewControllerContextTransitioning>)transitionContext {
    BaseViewController *fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    MainViewController * toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    UIImageView * maskImageView = [[UIImageView alloc] initWithImage:[self imageFromView:fromVC.view]];
    
    UITableViewCell * cell = [toVC.tableView cellForRowAtIndexPath:toVC.currentIndexPath];
    
    UIView *containerView = [transitionContext containerView];
    
    //拿到push的时候的快照
    UIView *CoverPageView = fromVC.animationView;
    maskImageView.frame = fromVC.view.bounds;
    [containerView addSubview:toVC.view];
    [containerView addSubview:maskImageView];
    [containerView addSubview:CoverPageView];
   // [containerView insertSubview:maskImageView atIndex:0];
   // fromVC.view.subviews.lastObject.alpha = 1.0;
    //设置三维旋转
    CATransform3D transform3D = CATransform3DIdentity;//单位矩阵
    transform3D.m34 = - 0.002;//m34（透视效果，要操作的这个对象要有旋转的角度，否则没有效果。正直/负值都有意义）
    containerView.layer.sublayerTransform = transform3D;
    
    [UIView animateWithDuration:0.5 animations:^{
        CoverPageView.frame = [cell convertRect:cell.bounds toView:containerView];
        CoverPageView.layer.transform = CATransform3DIdentity;
        
        maskImageView.frame = [cell convertRect:cell.bounds toView:containerView];
        
        maskImageView.alpha = 0;
    } completion:^(BOOL finished) {
        
        containerView.layer.sublayerTransform = CATransform3DIdentity;
        [CoverPageView removeFromSuperview];
        fromVC.animationView = nil;
        [maskImageView removeFromSuperview];
        [transitionContext completeTransition:YES];
        
        
//        if ([transitionContext transitionWasCancelled]) {
//            [transitionContext completeTransition:NO];
//        }else {
//           
//        }
    }];
}
// 可以在这里执行动画结束的操作

//- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
//
//}



@end
